package jch.learn.java.advanced.chapter4_network.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

// 回声服务器
// 可使用telnet 测试EchoServer
public class EchoServer {

    public static void main(String[] args) throws IOException {
        try (ServerSocket s = new ServerSocket(8189)) { // 将Socket服务绑定到端口8189
            try (Socket incoming = s.accept()) { // 等待连接
                InputStream inStream = incoming.getInputStream(); // 获取输入流
                OutputStream outStream = incoming.getOutputStream(); // 获取输出流
                try (Scanner in = new Scanner(inStream, "UTF-8")) {
                    PrintWriter out = new PrintWriter(new OutputStreamWriter(outStream, StandardCharsets.UTF_8), true);
                    out.println("Hello! Enter BYE to exit.");
                    boolean done = false;
                    while (!done && in.hasNextLine()) {
                        String line = in.nextLine();
                        out.println("Echo: " + line);
                        if (line.trim().equals("BYE")) done = true;
                    }
                }
            }
        }
    }

}
